<template>
	<view class="content">
		<form ref="myform">
			<input id="phoneNumber" placeholder="请输入您的手机号" v-model="formValue.phoneNumber" />
			<text>{{version}}</text>
			<button type="primary" @click="login">login</button>
			<text>{{$store.state.token}}</text>
		</form>
		<button type="default" @click="logout">logout</button>
		<text>-----------------</text>
		<button type="warn" @click="getuser">getuserinfo</button>
	</view>
</template>

<script>
	import {useStore} from 'vuex' //引入
	import store from '../../store' //引入，根据自己的目录来
	import {customerLogin, getUserinfo} from '../../api/user.js'
	export default {
		name: 'start',
		data() {
			const store = useStore(); //创建一个store
			console.log(store.state.token); //打印查看
			return {
				version: '',
				formValue: {
					phoneNumber: ''
				},
				userId: ''
			}
		},
		created() {
			this.version = wx.getAccountInfoSync().miniProgram.envVersion
			console.log(store.state.userinfo)
			this.formValue.phoneNumber = store.state.userinfo.phonenumber
		},
		methods: {
			login() {
				let that = this;
				if (!that.validate()) {
					return;
				}
				
				uni.login({
					provider: 'weixin',
					success: (res) => {
						console.log(store.state.token)
						console.log(store.state.updatetime)
						let exptime = new Date().getTime() - store.state.updatetime 
						console.log(exptime)
						if(store.state.token === '' || exptime > 240000){
							let data = {
								code: res.code,
								phoneNumber: that.formValue.phoneNumber
							}
							customerLogin(data).then(res2=>{
								console.log(res2)
								if(res2.code===200) {
									store.commit("updateToken", res2.data.token)
									store.commit("updateUserInfo", res2.data.userinfo)
									store.commit("updateUpdatetime", new Date().getTime())
								}
								if(res2.code===500) {
									uni.showToast({ title: res2.msg, icon: 'none' })
								}
							})
						}
					},
				})
			},
			logout() {
				let that = this
				uni.showModal({
					title: '提示',
					content: '确定退出系统吗？',
					showCancel: true,
					success: function(res) {
						if (res.confirm) {
							store.commit("updateToken",'')
							store.commit("updateUserInfo", '{}')
						} 
						if(res.cancel) {
							console.log("hidModal")
						}
					}
				})
			},
			validate() {
				const rules = [
					{ field:'phoneNumber', required: true, message: '请输入手机号码' }
				]
				      
				for (let i = 0; i < rules.length; i++) {
					let rule = rules[i]
			
					if (rule.required && !this.formValue.phoneNumber) {
						uni.showToast({ title: rule.message, icon: 'none' })
						return false
					}
				}
				      
				return true
			},
			
			getuser() {
				let that = this
				let data = {
					'userId': store.state.userinfo.userId
				}
				getUserinfo(data).then(res=>{
					console.log(res)
				})
			}
		}
	}
</script>